package com.equinox.consul.zuul.provider;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * 路由熔断
 * Zuul作为Netflix组件，可以与Ribbon、Eureka和Hystrix等组件相结合，实现负载均衡、熔断器的功能
 * @author Thinker
 *
 */
@Component
@Slf4j
public class MyFallbackProvider implements FallbackProvider{

	@Override
	public String getRoute() {
		// * 代表所有的消费熔断，也可以指定服务熔断
		return "*";
	}

	@Override
	public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
		log.info("route:{}",route);
		log.info("exception:{}",cause.getMessage());
		
		return new ClientHttpResponse() {
			
			@Override
			public HttpHeaders getHeaders() {
				HttpHeaders headers=new HttpHeaders();
				headers.setContentType(MediaType.APPLICATION_JSON);
				return headers;
			}
			/**
			 * 发送熔断时的反馈信息
			 */
			@Override
			public InputStream getBody() throws IOException {
				
				return new ByteArrayInputStream("sorry,the service is unavailable new.".getBytes());
			}
			
			@Override
			public String getStatusText() throws IOException {
				// TODO Auto-generated method stub
				return "ok";
			}
			
			@Override
			public HttpStatus getStatusCode() throws IOException {
				
				return HttpStatus.OK;
			}
			
			@Override
			public int getRawStatusCode() throws IOException {
				// TODO Auto-generated method stub
				return 200;
			}
			
			@Override
			public void close() {
				
				
			}
		};
	}

}
